package com.example.cloud.service.system.impl;

import com.example.cloud.dao.mongdb.system.MongoRoleRepository;
import com.example.cloud.dao.system.RoleRepository;
import com.example.cloud.mapper.system.RoleDao;
import com.example.cloud.model.system.Role;
import com.example.cloud.model.system.User;
import com.example.cloud.service.system.RoleService;
import com.example.cloud.utils.BusinessUtil;
import com.example.cloud.utils.RequestUtil;
import org.apache.log4j.Logger;
import org.beetl.sql.core.SQLManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by wangtao on 2018/2/3.
 */
@Service
public class RoleServiceImpl implements RoleService {

    private static final Logger logger = Logger.getLogger(RoleServiceImpl.class);

    @Autowired
    SQLManager sqlManager;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private MongoRoleRepository mongoRoleRepository;

    @Override
    public Role findOne(Long id) {
        return roleRepository.findOne(id);
    }

    @Override
    public Role findOneFromCache(Long id) {
        return mongoRoleRepository.findOne(id);
    }

    @Override
    public List<Role> findAll() {
        return mongoRoleRepository.findAll();
    }

    @Override
    @Transactional
    public void doSave(Role role) {
        // 新增
        if(role.getId() == null){
            // 添加组织机构
            User loginUser = RequestUtil.getLoginUser();
            if(loginUser != null){
                role.setOrganId(loginUser.getOrganId());
                role.setOrganName(loginUser.getOrganName());
                role.setAccountId(loginUser.getAccountId());
            }
        }
        // 保存实体
        BusinessUtil.appendRecord(role);
        roleRepository.save(role);
        // 同步缓存
        mongoRoleRepository.save(role);
    }

    @Override
    @Transactional
    public void doUpdate(Role role) {
        int count = sqlManager.updateTemplateById(role);
        if(count > 0){
            // 同步缓存
            mongoRoleRepository.save(role);
        }
    }

    @Override
    public void loadCache() {
        List<Role> list = roleRepository.findAll();
        if(!list.isEmpty()){
            mongoRoleRepository.save(list);
            logger.info("*******************角色已全部同步缓存*******************");
        }
    }
}
